<template>
  <div>
    <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
      <a-input-search
        v-model:value="searchRoomType"
        placeholder="请输入房型搜索"
        style="width: 200px; margin-right: 8px"
        @search="onSearch"
        @change="onSearchChange"
      />
      <a-button v-permission="'room:create'" type="primary" @click="showModal">新增房间</a-button>
    </div>

    <a-modal v-model:open="open" :title="isEdit ? '编辑房间' : '新增房间'" @ok="handleOk" @cancel="resetForm">
      <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="酒店ID" name="hotelId">
          <a-input v-model:value="formState.hotelId" />
        </a-form-item>
        <a-form-item label="房型" name="roomType">
          <a-input v-model:value="formState.roomType" />
        </a-form-item>
        <a-form-item label="价格" name="price">
          <a-input v-model:value="formState.price" type="number" />
        </a-form-item>
        <a-form-item label="库存" name="inventory">
          <a-input v-model:value="formState.inventory" type="number" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-table bordered :data-source="dataSource" :columns="columns" :loading="loading" :pagination="false" row-key="id">
      <template #bodyCell="{ column, text, record }">
        <template v-if="['roomType','price','inventory'].includes(column.dataIndex)">
          <div class="editable-cell">
            <div v-if="editableData[record.id]" class="editable-cell-input-wrapper">
              <a-input v-model:value="editableData[record.id][column.dataIndex]" @pressEnter="save(record.id)" />
              <check-outlined class="editable-cell-icon-check" @click="save(record.id)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              <span>{{ text || ' ' }}</span>
              <edit-outlined v-permission="'room:update'" class="editable-cell-icon" @click="edit(record.id)" />
            </div>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createdAt'">{{ formatDate(text) }}</template>
        <template v-else-if="column.dataIndex === 'operation'">
          <span>
            <a-button v-permission="'room:update'" type="link" size="small" @click="edit(record.id)" style="margin-right: 8px">编辑</a-button>
            <a-popconfirm v-permission="'room:delete'" v-if="dataSource.length" title="确定要删除该房间吗？" @confirm="onDelete(record.id)">
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </span>
        </template>
      </template>
    </a-table>

    <div style="margin-top: 16px; text-align: right;">
      <a-pagination v-model:current="current" :total="total" :page-size="pageSize" show-size-changer :page-size-options="['8','10','20']" @change="onChange" />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { roomAPI } from '@/api/room'
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue'

const searchRoomType = ref('')
const originalDataSource = ref([])
const dataSource = ref([])
const current = ref(1)
const total = ref(0)
const pageSize = ref(8)
const loading = ref(false)

const formRef = ref()
const labelCol = { span: 6 }
const wrapperCol = { span: 16 }
const open = ref(false)
const isEdit = ref(false)

const formState = reactive({ id: undefined, hotelId: undefined, roomType: '', price: '', inventory: '' })

const rules = {
  hotelId: [{ required: true, message: '请输入酒店ID', trigger: 'blur' }],
  roomType: [{ required: true, message: '请输入房型', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  inventory: [{ required: true, message: '请输入库存', trigger: 'blur' }]
}

const columns = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '酒店ID', dataIndex: 'hotelId', width: 100 },
  { title: '房型', dataIndex: 'roomType' },
  { title: '价格', dataIndex: 'price', width: 120 },
  { title: '库存', dataIndex: 'inventory', width: 100 },
  { title: '创建时间', dataIndex: 'createdAt', width: 180 },
  { title: '操作', dataIndex: 'operation', width: 150 }
]

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const initData = async () => {
  loading.value = true
  try {
    const res = await roomAPI.list(undefined, current.value, pageSize.value, searchRoomType.value)
    const payload = res.data?.data || {}
    const list = Array.isArray(payload.list) ? payload.list : (Array.isArray(payload.data) ? payload.data : [])
    originalDataSource.value = list
    dataSource.value = list
    total.value = Number(payload.total || list.length)
  } catch (e) {
    message.error('获取房间列表失败')
  } finally {
    loading.value = false
  }
}

const onSearch = () => {
  // 重置到第一页
  current.value = 1
  // 重新加载数据
  initData()
}

const onSearchChange = () => {
  if (!searchRoomType.value) {
    // 清空搜索时重新加载数据
    current.value = 1
    initData()
  }
}

const onChange = (page, size) => {
  current.value = page
  pageSize.value = size
  initData()
}

const showModal = () => { isEdit.value = false; open.value = true }
const resetForm = () => { formRef.value?.resetFields() }

const handleOk = async () => {
  try {
    if (isEdit.value) {
      await roomAPI.update(formState)
    } else {
      await roomAPI.create(formState)
    }
    open.value = false
    resetForm()
    initData()
  } catch (e) {
    message.error('保存失败')
  }
}

const editableData = reactive({})
const edit = (id) => { isEdit.value = true; editableData[id] = { ...dataSource.value.find(i => i.id === id) } }
const save = async (id) => {
  try {
    await roomAPI.update(editableData[id])
    Object.assign(dataSource.value.find(i => i.id === id), editableData[id])
    delete editableData[id]
    message.success('更新成功')
  } catch (e) { message.error('更新失败') }
}
const onDelete = async (id) => { try { await roomAPI.remove(id); initData() } catch (e) { message.error('删除失败') } }

onMounted(() => { initData() })
</script>

<style scoped>
.editable-cell { position: relative; }
.editable-cell-input-wrapper,
.editable-cell-text-wrapper { padding-right: 24px; }
.editable-cell-text-wrapper { padding: 5px 24px 5px 5px; }
.editable-cell-icon, .editable-cell-icon-check { position: absolute; right: 0; width: 20px; cursor: pointer; }
.editable-cell-icon { margin-top: 4px; display: none; }
.editable-cell-icon-check { line-height: 28px; }
.editable-cell-icon:hover, .editable-cell-icon-check:hover { color: #108ee9; }
.editable-cell:hover .editable-cell-icon { display: inline-block; }
</style>

